#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <fstream>
#include <sstream>

using std::cout;
using std::endl;
using std::cerr;
using std::string;
using std::map;
using std::unordered_map;
using std::ifstream;
using std::istringstream;

class TransWord
{
public:
    TransWord()
    {
    }

    void buildMap(const string &filename)
    {
        ifstream ifs(filename);
        if(!ifs)
        {
            cerr << "ifstream open " << filename << " error!" << endl;
            return;
        }

        string key;
        string value;
        //使用ifs读取每行需要转换的单词，value存待转换的单词（包括一个空格）
        while(ifs >> key && getline(ifs, value))
        {
            if(value.size() > 1)
            {
                //去除空格
                _um[key] = value.substr(1);  //welcome
            }
        }

        ifs.close();
    }

    const string &transform(const string &line)
    {
        //查看单词
        auto mapIt = _um.find(line);
    
        if(mapIt != _um.end())
        {
            return _um.find(line)->second;
        }
        else
        {
            return line;
        }
    }

    void trans(const string &filename)
    {
        ifstream ifs(filename);
        if(!ifs)
        {
            cerr << "open file " << filename << " error!" << endl;
            return;
        }

        string line;
        string word;
        while(getline(ifs, line))
        {
            //firstWord要定义在这个地方，否则放在while循环
            //的外部并初始化为true，第二行开始得每行多个空格
            bool firstWord = true;
    
            //iss也得定义在这个while内，如果定义在这个循环外，
            //则整个循环只有一个内存流is，只能处理一行  
            cout << "line = " << line << endl;
            istringstream iss(line);
            while(iss >> word)
            {
                word = transform(word);
                if(firstWord)
                {
                    firstWord = false;
                }
                else
                {
                    cout << " ";
                }
                cout << word;    
            }
            cout << endl;
        }

        ifs.close();
    }
private:
    unordered_map<string, string> _um;
};

int main(int argc, char *argv[])
{
    TransWord tw;
    tw.buildMap("map.txt");
    tw.trans("file.txt");

    return 0;
}
